package com.zzx.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.zzx.entity.*;
import com.zzx.mapper.TProductOrderMapper;
import com.zzx.service.*;
import com.zzx.utils.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zzx
 * @description 针对表【t_product_order】的数据库操作Service实现
 * @createDate 2024-11-30 17:14:43
 */
@Service
public class TProductOrderServiceImpl extends ServiceImpl<TProductOrderMapper, TProductOrder>
        implements TProductOrderService {

    @Resource
    private TProductOrderDeptService tProductOrderDeptService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TProductOrder param) {

        if (ObjectUtils.isEmpty(param.getProductOrderId())) {
            param.setProductOrderId(IdUtil.getSnowflakeNextId());
        } else {
            EntityUtils.mergeNonNullProperties(this.getBaseMapper().selectById(param.getProductOrderId()), param);
        }

        this.saveOrUpdate(param);

        if (!ObjectUtils.isEmpty(param.getTProductOrderDepts())) {
            List<Long> collect = param.getTProductOrderDepts().stream().map(e -> e.getProductOrderDeptId()).collect(Collectors.toList());
            if (collect.size()>0) {
                tProductOrderDeptService.removeByIds(collect);
            }
            param.getTProductOrderDepts().forEach(e -> {
                e.setProductOrderDeptId(IdUtil.getSnowflakeNextId());
                e.setProductOrderId(param.getProductOrderId());
            });
            tProductOrderDeptService.saveBatch(param.getTProductOrderDepts());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TProductOrder param) {
        this.removeById(param.getProductOrderId());
    }

    @Override
    public List<TProductOrder> selectBy(TProductOrder param) {
        LambdaQueryWrapper<TProductOrder> wrapper = new LambdaQueryWrapper<>(TProductOrder.class);
        if (!ObjectUtils.isEmpty(param.getProductOrderNum())) {
            wrapper.like(TProductOrder::getProductOrderNum, param.getProductOrderNum());
        }
        if (!ObjectUtils.isEmpty(param.getProductOrderId())) {
            wrapper.eq(TProductOrder::getProductOrderId, param.getProductOrderId());
        }
        // 多租户拦截器会自动添加 company_id 条件
        List<TProductOrder> tProductOrders = this.getBaseMapper().selectList(wrapper);
        return tProductOrders;
    }

    @Override
    public TProductOrder findById(Long id) {
        TProductOrder tProductOrder = this.getBaseMapper().selectById(id);
        if (!ObjectUtils.isEmpty(tProductOrder)) {
            LambdaQueryWrapper<TProductOrderDept> tProductOrderDeptWrapper = new LambdaQueryWrapper<>();
            tProductOrderDeptWrapper.eq(TProductOrderDept::getProductOrderId, tProductOrder.getProductOrderId());
            tProductOrder.setTProductOrderDepts(tProductOrderDeptService.list(tProductOrderDeptWrapper));
        }
        return tProductOrder;
    }

    /**
     * 查询用户可提交的工作列表
     * @param param
     * @return
     */
    @Override
    public List<TProductOrder> selectSubmitList(TProductOrder param) {
        // 多租户拦截器会自动添加 company_id 条件
        List<TProductOrder> tProductOrders = this.getBaseMapper().selectSubmitList(param);
        return tProductOrders;

//        LambdaQueryWrapper<TProductOrder> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(TProductOrder::getCompanyId, UserContext.getCompanyId());
//        wrapper.orderByDesc(TProductOrder::getCreateTime);
//        List<TProductOrder> tProductOrders = this.getBaseMapper().selectList(wrapper);
//        List<TProductOrderProduct> tProductOrderProducts = new ArrayList<>();

//        param.setCompanyId(UserContext.getCompanyId());
//        List<TProductOrder> tProductOrders = this.getBaseMapper().selectSubmitList(param);
//        Map<String, List<TProductOrder>> collect = tProductOrders.stream().collect(Collectors.groupingBy(TProductOrder::getProductOrderNum));
//        return collect;

//        MPJLambdaWrapper<TProductOrder> wrapper = new MPJLambdaWrapper<TProductOrder>()
//                .select(TProductOrder::getProductOrderId)
//                .select(TProductOrder::getProductOrderNum)
//                .select(TProductOrder::getProductOrderType)
//                .leftJoin(TProductOrderProduct.class, TProductOrderProduct::getProductOrderId, TProductOrder::getProductOrderId)
//                .selectAs(TProductOrderProduct::getProductOrderProductId, TProductOrder::getTProductOrderProducts)
//                .selectAs(TProductOrderProduct::getProductId, TProductOrder::getTProductOrderProducts)
//                .selectAs(TProductOrderProduct::getProductColor, TProductOrder::getTProductOrderProducts)
//                .selectAs(TProductOrderProduct::getProductSize, TProductOrder::getTProductOrderProducts)
//                .selectAs(TProductOrderProduct::getCountNum, TProductOrder::getTProductOrderProducts)
//                .leftJoin(TProduct.class, TProduct::getProductId, TProductOrderProduct::getProductId)
//                .selectAs(TProduct::getProductName, TProductOrder::getTProductOrderProducts)
//                .orderByDesc(TProductOrder::getCreateTime);
//        List<TProductOrder> tProductOrders = this.getBaseMapper().selectJoinList(TProductOrder.class, wrapper);
//        return tProductOrders;
    }

    /**
     * 查询用户可提交的工序列表
     * @param param
     * @return
     */
    @Resource
    private TProductGxGroupService tProductGxGroupService;

    @Resource
    private TProductGxService tProductGxService;

    @Resource
    private TGxService tGxService;
    @Override
    public List<TProductGxGroup> selectSubmitGXList(TProductOrder param) {
        // 注意：这里需要手动传入 companyId，因为是参数传递
        List<TGx> tGxes = tGxService.list(new LambdaQueryWrapper<>(TGx.class).eq(TGx::getCompanyId, param.getCompanyId()));
        if (ObjectUtils.isEmpty(tGxes)) {
            return new ArrayList<TProductGxGroup>();
        }
        // 将工序信息转换成Map
        Map<Long, TGx> gxMap = tGxes.stream().collect(Collectors.toMap(TGx::getGxId, gx -> gx));
        
        // 查询产品工序分组（多租户自动过滤）
        List<TProductGxGroup> list = tProductGxGroupService.list(new LambdaQueryWrapper<TProductGxGroup>()
                .eq(TProductGxGroup::getProductId, param.getProductId())
                .orderByAsc(TProductGxGroup::getSort));
        
        for (TProductGxGroup tProductGxGroup : list) {
            // 查询工序明细（多租户自动过滤）
            List<TProductGx> tProductGxes = tProductGxService.list(new LambdaQueryWrapper<TProductGx>()
                    .eq(TProductGx::getProductGxGroupId, tProductGxGroup.getProductGxGroupId()));
            tProductGxes.forEach(tProductGx -> tProductGx.setGxName(gxMap.get(tProductGx.getGxId()).getGxName()));
            tProductGxGroup.setTProductGxs(tProductGxes);
        }
        return list;
    }
}




